package city.spring.service.mealService.impl;

import city.spring.domain.entity.mealService.FoodInfoEntity;
import city.spring.domain.entity.mealService.MealTimeEntity;
import city.spring.domain.entity.mealService.RecipesEntity;
import city.spring.domain.entity.mealService.RecipesWeekEntity;
import city.spring.modules.ext.EntityExtUtils;
import city.spring.modules.ext.entity.RecipesDiseaseExt;
import city.spring.modules.ext.entity.RecipesMealTimeExt;
import city.spring.modules.ext.service.RecipesDiseaseExtService;
import city.spring.modules.ext.service.RecipesMealTimeExtService;
import city.spring.modules.health.entity.DiseaseEntity;
import city.spring.modules.health.service.DiseaseService;
import city.spring.repository.mealService.RecipesRepository;
import city.spring.service.mealService.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Throwable.class)
public class RecipesServiceImpl extends ServiceImpl<RecipesRepository, RecipesEntity> implements RecipesService {

    private RecipesWeekService recipesWeekService;
    private FoodInfoService foodInfoService;
    private FoodTypeService foodTypeService;
    private MealTimeService mealTimeService;
    private DiseaseService diseaseService;
    private RecipesDiseaseExtService recipesDiseaseExtService;
    private RecipesMealTimeExtService recipesMealTimeExtService;

    public RecipesServiceImpl(RecipesWeekService recipesWeekService, FoodInfoService foodInfoService, RecipesDiseaseExtService recipesDiseaseExtService, FoodTypeService foodTypeService, MealTimeService mealTimeService, RecipesMealTimeExtService recipesMealTimeExtService, DiseaseService diseaseService) {
        this.recipesWeekService = recipesWeekService;
        this.foodInfoService = foodInfoService;
        this.foodTypeService = foodTypeService;
        this.diseaseService = diseaseService;
        this.recipesDiseaseExtService = recipesDiseaseExtService;
        this.mealTimeService = mealTimeService;
        this.recipesMealTimeExtService = recipesMealTimeExtService;
    }

    @Override
    public void saveRecipes(RecipesEntity entity) {
        boolean save = save(entity);
        setRecipesMealTime(entity);
        if (!save) {
            throw new RuntimeException("保存失败！");
        }
    }

    @Override
    public void updateRecipes(RecipesEntity entity) {
        boolean update = lambdaUpdate()
                .set(RecipesEntity::getRecipesName, entity.getRecipesName())
                .set(RecipesEntity::getRecipesCode, entity.getRecipesCode())
                .set(RecipesEntity::getRecipesPrize, entity.getRecipesPrize())
                .set(RecipesEntity::getRemark, entity.getRemark())
                .set(RecipesEntity::getRecipesType, entity.getRecipesType())
                .eq(RecipesEntity::getId, entity.getId())
                .update();
        if (!update) {
            throw new RuntimeException("保存失败！");
        }
    }

    @Override
    public void updateRecipesMenu(String id, List<String> idList) {
        RecipesEntity recipesEntity = getById(id);
        List<DiseaseEntity> diseaseEntities = new LinkedList<>();
        if (idList.size() != 0) {
            for (int i = 0; i < idList.size(); i++) {
                diseaseEntities.add(i, diseaseService.getById(idList.get(i)));
            }
        } else if (idList.size() == 0) {
            System.out.println("无禁忌人群！");
            diseaseEntities = null;
        }
        recipesEntity.setDisease(diseaseEntities);
        updateRecipes(recipesEntity);
        setRecipesDisease(recipesEntity);
    }

    @Override
    public void updateRecipesMealTime(RecipesEntity entity) {
        setRecipesMealTime(entity);
    }

    @Override
    public void deleteRecipes(String primaryKey) {
        removeById(primaryKey);
        setRecipesMealTime(getById(primaryKey));
        setRecipesDisease(getById(primaryKey));
        List<RecipesWeekEntity> entities = recipesWeekService.getRecipesWeek(primaryKey);
        for (int i = 0; i < entities.size(); i++) {
            recipesWeekService.deleteRecipesWeek(entities.get(i).getId());
        }
    }

    @Override
    public void deleteRecipes(List<String> primaryKeys) {
        removeByIds(primaryKeys);
        for (int i = 0; i < primaryKeys.size(); i++) {
            setRecipesMealTime(getById(primaryKeys.get(i)));
            setRecipesDisease(getById(primaryKeys.get(i)));
            List<RecipesWeekEntity> entities = recipesWeekService.getRecipesWeek(primaryKeys.get(i));
            for (int j = 0; j < entities.size(); j++) {
                recipesWeekService.deleteRecipesWeek(entities.get(j).getId());
            }
        }
    }

    @Override
    public Map<String, List<FoodInfoEntity>> loadTypeFoodInfo(RecipesEntity entity) {
        loadFoodInfo(entity);
        List<FoodInfoEntity> foodInfoEntities = entity.getFoodInfoEntities();
        if (foodInfoEntities.size() == 0) {
            foodInfoEntities = foodInfoService.list();
        }
        List<List<FoodInfoEntity>> recipesFood = new LinkedList<>();
        foodInfoEntities.stream().collect(Collectors.groupingBy(FoodInfoEntity::getFoodId, Collectors.toList()))
                .forEach((foodId, foodListByfoodId) -> {
                    recipesFood.add(foodListByfoodId);
                });
        Map<String, List<FoodInfoEntity>> newMap = new HashMap<>();
//        FoodTypeEntity foodTypeEntity =foodTypeService
//                .lambdaQuery()
//                .eq(FoodTypeEntity::getType,foodTypeService
//                        .lambdaQuery()
//                        .eq(FoodTypeEntity::getId,recipesFood.get(0).get(0).getFoodId()))
//                .one();
        for (int i = 0; i < recipesFood.size(); i++) {
            newMap.put(foodTypeService.getById(recipesFood.get(i).get(0).getFoodId()).getType(), recipesFood.get(i));
        }
//        recipesFood.forEach((foodInfoEntities1 -> {
//            System.out.println(foodInfoEntities1.size());
//            foodInfoEntities.forEach((foodInfoEntity -> System.out.println(foodInfoEntity.getFoodId())));
//        }));
        return newMap;
    }

    @Override
    public void loadFoodInfo(RecipesEntity entity) {
        loadDisease(entity);
        List<DiseaseEntity> diseaseEntities = entity.getDisease();
        List<FoodInfoEntity> foodInfoEntities = new LinkedList<>();
        List<String> diseaseIdList = new LinkedList<>();
        if (diseaseEntities.size() != 0) {
            for (int i = 0; i < diseaseEntities.size(); i++) {
                diseaseIdList.add(i, diseaseEntities.get(i).getId());
            }
            List<FoodInfoEntity> normalFoodInfoEntities = foodInfoService.getNormalDiseaseFood(diseaseIdList);
            List<FoodInfoEntity> forbiddenFoodInfoEntities = foodInfoService.getDiseaseFood(diseaseIdList, 0);
            for (int i = 0; i < forbiddenFoodInfoEntities.size(); i++) {
                forbiddenFoodInfoEntities.get(i).setForbiddenOrRecommend("不推荐");
            }
            List<FoodInfoEntity> recommendFoodInfoEntities = foodInfoService.getDiseaseFood(diseaseIdList, 1);
            for (int i = 0; i < recommendFoodInfoEntities.size(); i++) {
                recommendFoodInfoEntities.get(i).setForbiddenOrRecommend("推荐");
            }
            foodInfoEntities.addAll(normalFoodInfoEntities);
            foodInfoEntities.addAll(forbiddenFoodInfoEntities);
            foodInfoEntities.addAll(recommendFoodInfoEntities);
        } else if (diseaseEntities.size() == 0) {
            foodInfoEntities = foodInfoService.list();
        }
        entity.setFoodInfoEntities(foodInfoEntities);
    }

    @Override
    public void loadFoodInfo(List<RecipesEntity> entities) {
        entities.forEach(this::loadFoodInfo);
    }

    @Override
    public void loadMealTime(RecipesEntity entity) {
        List<MealTimeEntity> weekMealEntities = mealTimeService.getRecipesMealTime(entity.getId());
        entity.setMealTime(weekMealEntities);
    }

    @Override
    public void loadMealTime(List<RecipesEntity> entities) {
        entities.forEach(this::loadMealTime);
    }

    @Override
    public void loadDisease(RecipesEntity entity) {
        List<DiseaseEntity> disease = diseaseService.getRecipesDisease(entity.getId());
        entity.setDisease(disease);
    }

    @Override
    public void loadDisease(List<RecipesEntity> entities) {
        entities.forEach(this::loadDisease);
    }

    @Override
    public void setRecipesDisease(RecipesEntity entity) {
        EntityExtUtils.repairRelation(recipesDiseaseExtService, entity,
                RecipesEntity::getId, RecipesEntity::getDisease, DiseaseEntity::getId,
                RecipesDiseaseExt::new, RecipesDiseaseExt::getDiseaseId);
    }


    @Override
    public void setRecipesMealTime(RecipesEntity entity) {
        EntityExtUtils.repairRelation(recipesMealTimeExtService, entity,
                RecipesEntity::getId, RecipesEntity::getMealTime, MealTimeEntity::getId,
                RecipesMealTimeExt::new, RecipesMealTimeExt::getRecipesId);
    }

}
